package com.example.forumsystem.demos.web.service.impl;

import com.example.forumsystem.demos.web.common.Constans;
import com.example.forumsystem.demos.web.common.ResultCode;
import com.example.forumsystem.demos.web.exception.ApplicationException;
import com.example.forumsystem.demos.web.mapper.ArticleInfoMapper;
import com.example.forumsystem.demos.web.mapper.BoardInfoMapper;
import com.example.forumsystem.demos.web.mapper.UserInfoMapper;
import com.example.forumsystem.demos.web.model.ArticleInfo;
import com.example.forumsystem.demos.web.model.BoardInfo;
import com.example.forumsystem.demos.web.model.Result;
import com.example.forumsystem.demos.web.model.UserInfo;
import com.example.forumsystem.demos.web.service.IArticleService;
import com.example.forumsystem.demos.web.service.IBoardService;
import com.example.forumsystem.demos.web.service.IUserService;
import com.example.forumsystem.demos.web.utils.StringUtil;
import io.micrometer.core.lang.NonNull;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {
    @Autowired
    private ArticleInfoMapper articleInfoMapper;
    @Autowired
    private IUserService userService;
    @Autowired
    private IBoardService boardService;
    @Override
    public void create(ArticleInfo article) {

        if (article == null || article.getUserId() == null || article.getBoardId() == null
                || StringUtil.isEmpty(article.getTitle())
                || StringUtil.isEmpty(article.getContent()) ) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 设置默认值
        article.setVisitCount(0); // 访问数
        article.setReplyCount(0); // 回复数
        article.setLikeCount(0);  // 点赞数
        article.setDeleteState((byte) 0);
        article.setState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);

        Integer res = articleInfoMapper.insertSelective(article);
        if (res != 1){
            log.warn("新增帖子失败，传入的帖子是：" + article.toString());
            throw new ApplicationException(Result.fail("发帖失败, 请联系管理员"));
        }

        // 判断在数据库在是否有对应的用户
        UserInfo user = userService.selectById(article.getUserId());
        if (user == null) {
            log.warn(ResultCode.FAILED_CREATE.toString() + ", 发贴失败, user id = " + article.getUserId());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_CREATE));
        }
        userService.addOneArticleCountById(article.getUserId());

        // 判断在数据库在是否有对应的板块
        BoardInfo board = boardService.selectById(article.getBoardId());
        if (board == null) {
            log.warn(ResultCode.FAILED_CREATE.toString() + ", 发贴失败, board id = " + article.getBoardId());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_CREATE));
        }

        boardService.addOneArticleCountById(article.getBoardId());
    }

    @Override
    public List<ArticleInfo> selectAll() {
        List<ArticleInfo> articles = articleInfoMapper.selectAll();
        if (articles == null || articles.size() == 0){
            log.info("没有文章");
        }
        return articles;
    }

    @Override
    public List<ArticleInfo> selectAllByBoardId(Long boardId) {
        if (boardId == null || boardId < 0){
            log.warn("传来的板块id错误， id为：" + boardId);
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        List<ArticleInfo> articles = articleInfoMapper.selectAllByBoardId(boardId);
        if (articles == null || articles.size() < 0){
            log.warn("没有查询到板块内的文章，传来的板块idid为：" + boardId);
            throw new ApplicationException(Result.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        return articles;
    }

    @Override
    public ArticleInfo selectDetailById(Long id) {
        if (id == null || id < 0){
            log.warn("传来的文章id错误， id为：" + id);
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        ArticleInfo article = articleInfoMapper.selectDetailById(id);

        // 更新帖子的访问次数
        ArticleInfo updateArticle = new ArticleInfo();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount() + 1);

        int row = articleInfoMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(Result.fail(ResultCode.ERROR_SERVICES));
        }
        return article;
    }

    @Override
    public void modify(Long id, String title, String content) {
        if (id == null || id < 0 || StringUtil.isEmpty(title) || StringUtil.isEmpty(content)){
            log.warn("传来的参数有误，id为：" + id + ", title为：" + title + ", content为：" + content);
            new ApplicationException(new Result(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        ArticleInfo article = new ArticleInfo();
        article.setTitle(title);
        article.setId(id);
        article.setContent(content);
        article.setUpdateTime(new Date());
        int row = articleInfoMapper.updateByPrimaryKeySelective(article);
        if (row != 1) {
            log.warn("更新操作失败");
            throw new ApplicationException(Result.fail(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public ArticleInfo selectById(Long id) {
        if (id == null || id < 0){
            log.warn("传来的id有误, id为：" + id);
        }

        return articleInfoMapper.selectByPrimaryKey(id);
    }

    @Override
    public void addOneLikeCount(Long id) {
        if (id == null || id <= 0) {
            log.warn("参数校验失败, id为：" + id);
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        ArticleInfo article = articleInfoMapper.selectByPrimaryKey(id);
        // 没查到该帖子，或者该帖子是删除状态，直接返回
        if (article == null || article.getDeleteState() == 1) {
            log.info("帖子是删除状态");
            throw new ApplicationException(Result.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        // 帖子状态异常，直接返回
        if (article.getState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_ARTICLE_BANNED));
        }

        ArticleInfo updateArticle = new ArticleInfo();
        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(article.getLikeCount() + 1);
        updateArticle.setUpdateTime(new Date());

        int row = articleInfoMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            log.warn("更新失败");
            throw new ApplicationException(Result.fail(ResultCode.ERROR_SERVICES));
        }
    }

    @Transactional
    @Override
    public void deleteById(Long id) {
        if (id == null || id <= 0) {
            log.warn("参数校验失败，传入的id有误，articleId：" + id);
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 根据Id查询帖子信息，如果帖子是删除状态就返回
        ArticleInfo article = articleInfoMapper.selectByPrimaryKey(id);
        if (article == null || article.getDeleteState() == 1) {
            log.warn( "帖子不存在, articleId为：" + id);
            throw new ApplicationException(Result.fail(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }

        ArticleInfo updateArticle = new ArticleInfo();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte) 1);

        int row = articleInfoMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            log.warn("删除帖子失败");
            throw new ApplicationException(Result.fail(ResultCode.ERROR_SERVICES));
        }
        // 更新版块中的帖子数量
        boardService.cutOneArticleCountById(article.getBoardId());
        // 更新用户发帖数
        userService.cutOneArticleCountById(article.getUserId());
        log.info("删除帖子成功, article id = " + article.getId() + ", user id = " + article.getUserId() + ".");
    }

    @Override
    public void addOneReplyCountById(Long articleId) {
        if (articleId == null || articleId <= 0) {
            log.warn("参数校验失败，传入的帖子id为：" + articleId);
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        ArticleInfo article = articleInfoMapper.selectByPrimaryKey(articleId);
        ArticleInfo updateArticle = new ArticleInfo();
        updateArticle.setId(article.getId());
        // 让回复数+1
        updateArticle.setReplyCount(article.getReplyCount() + 1);
        updateArticle.setUpdateTime(new Date());

        int row = articleInfoMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            log.warn("新增文章的回复数失败");
            throw new ApplicationException(Result.fail(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public List<ArticleInfo> selectByUserId(Long userId) {
        if (userId == null || userId < 0){
            log.warn("参数校验失败，传入的帖子id为：" + userId);
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        return articleInfoMapper.selectByUserId(userId);
    }
}

